package com.google.code.mochaccino.framework.transaction;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;

public class TransactionAspectService {
	private DataSource ds;
	private int id = 1;

	public TransactionAspectService( DataSource ds ) {
		this.ds = ds;
	}

	@Transactional
	public void createDB() throws SQLException {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = ds.getConnection();
			stmt = conn.createStatement();
			stmt.execute( "CREATE TABLE TESTTABLE (col1 int, col2 int, PRIMARY KEY (col1) )" );
		} finally {
			stmt.close();
			conn.close();
		}
	}

	@Transactional( propagation = Propagation.MANDATORY )
	public int getMax() throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = ds.getConnection();
			stmt = conn.prepareStatement( "SELECT MAX(col1) FROM TESTTABLE" );
			rs = stmt.executeQuery();
			rs.next();
			return rs.getInt( 1 );
		} finally {
			rs.close();
			stmt.close();
			conn.close();
		}
	}

	@Transactional( propagation = Propagation.MANDATORY )
	public void insertMandatory() throws SQLException {
		insert();
	}

	@Transactional
	public void insertRequired() throws SQLException {
		insert();
	}

	@Transactional( propagation = Propagation.MANDATORY )
	private void insert() throws SQLException {
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = ds.getConnection();
			stmt = conn.prepareStatement( "INSERT INTO TESTTABLE (col1, col2) VALUES (?,?)" );
			stmt.setInt( 1, id );
			stmt.setInt( 2, id );
			stmt.executeUpdate();
			id++;
		} finally {
			if ( stmt != null ) {
				stmt.close();
			}

			if ( conn != null ) {
				conn.close();
			}
		}
	}

	@Transactional( propagation = Propagation.REQUIRES_NEW )
	public void insertRequiredNew() throws SQLException {
		insert();
	}
}



